<template>
  <view class="orders-container">
    <!-- 状态筛选标签栏 -->
    <view class="filter-tabs">
      <view 
        v-for="(tab, index) in statusTabs" 
        :key="index"
        class="filter-tab"
        :class="{ active: currentStatus === tab.value }"
        @click="switchStatus(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-list">
      <view 
        v-for="order in orderList" 
        :key="order.id"
        class="order-item"
        @click="goToOrderDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-number">{{ order.order_number }}</text>
          <text class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </text>
        </view>
        
        <view class="order-info">
          <view class="info-row">
            <text class="info-label">车牌号：</text>
            <text class="info-value">{{ order.license_plate }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">预计时间：</text>
            <text class="info-value">{{ formatDateTime(order.planned_start_time) }} - {{ formatDateTime(order.planned_end_time) }}</text>
          </view>
          <view class="info-row" v-if="order.actual_start_time">
            <text class="info-label">实际时间：</text>
            <text class="info-value">{{ formatDateTime(order.actual_start_time) }} - {{ order.actual_end_time ? formatDateTime(order.actual_end_time) : '进行中' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">金额：</text>
            <text class="info-value amount">¥{{ order.final_amount }}</text>
          </view>
        </view>
        
        <!-- 右箭头 -->
        <view class="arrow-right">
          <text class="arrow-icon">></text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && orderList.length === 0" class="empty-state">
        <text class="empty-text">暂无订单数据</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { request } from '../../utils/request.js'
import { parkingOperatorGuard } from '../../utils/roleGuard.js'

// 响应式数据
const loading = ref(false)
const currentStatus = ref('all')
const currentPage = ref(1)
const hasMore = ref(true)
const orderList = ref([])
const statusTabs = reactive([
  { label: '全部', value: 'all' },
  { label: '待支付', value: 'pending_payment' },
  { label: '进行中', value: 'in_progress' },
  { label: '待补款', value: 'pending_additional_payment' },
  { label: '已完成', value: 'completed' }
])

/**
 * 切换状态筛选
 */
const switchStatus = (status) => {
  if (currentStatus.value === status) return
  
  currentStatus.value = status
  currentPage.value = 1
  hasMore.value = true
  orderList.value = []
  loadOrders()
}

/**
 * 加载订单列表
 */
const loadOrders = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: 20
    }
    
    if (currentStatus.value !== 'all') {
      params.status = currentStatus.value
    }

    const response = await request({
      url: '/api/parking-operator/orders',
      method: 'GET',
      data: params
    })

    if (response.success) {
      const newOrders = response.data.list || []
      
      if (currentPage.value === 1) {
        orderList.value = newOrders
      } else {
        orderList.value = [...orderList.value, ...newOrders]
      }
      
      hasMore.value = newOrders.length >= 20
    } else {
      uni.showToast({
        title: response.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
    uni.stopPullDownRefresh()
  }
}

/**
 * 刷新订单列表
 */
const refreshOrders = () => {
  currentPage.value = 1
  hasMore.value = true
  loadOrders()
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value++
  loadOrders()
}

/**
 * 跳转到订单详情页面
 */
const goToOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/parking-operator/order-detail?id=${orderId}`
  })
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    'pending_payment': '待支付',
    'in_progress': '进行中',
    'pending_additional_payment': '待补款',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  return `status-${status}`
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/**
 * 格式化日期时间为输入框格式
 */
const formatDateTimeForInput = (dateTime) => {
  if (!dateTime) return ''
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

// 生命周期钩子
onLoad(() => {
  loadOrders()
})

onPullDownRefresh(() => {
  refreshOrders()
})

// 应用权限守卫
if (parkingOperatorGuard && parkingOperatorGuard.created) {
  parkingOperatorGuard.created.call({})
}
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 筛选标签栏 */
.filter-tabs {
  display: flex;
  background: white;
  padding: 20rpx 30rpx;
  border-bottom: 2rpx solid #eee;
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
  border-radius: 10rpx;
  margin: 0 10rpx;
}

.filter-tab.active {
  color: #007aff;
  background: #e6f3ff;
  font-weight: bold;
}

/* 订单列表 */
.orders-list {
  padding: 30rpx;
}

.order-item {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.order-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.order-status {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  color: white;
}

.status-pending_payment {
  background: #ff9500;
}

.status-in_progress {
  background: #007aff;
}

.status-pending_additional_payment {
  background: #ff9500;
}

.status-completed {
  background: #34c759;
}

.status-cancelled {
  background: #ff3b30;
}

.order-info {
  space-y: 10rpx;
}

.info-row {
  display: flex;
  margin-bottom: 15rpx;
  font-size: 28rpx;
}

.info-label {
  color: #666;
  width: 160rpx;
}

.info-value {
  color: #333;
  flex: 1;
}

.info-value.amount {
  color: #ff6b35;
  font-weight: bold;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-more-text {
  font-size: 28rpx;
  color: #007aff;
}

/* 右箭头 */
.arrow-right {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.arrow-icon {
  font-size: 32rpx;
  color: #ccc;
  font-weight: bold;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}
</style>